using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Media;
using Avalonia.Media.Imaging;

namespace Digitalmes.AvaloniaUI.Behaviors;

/// <summary>
/// 缩略图
/// </summary>
public class ThumbnailOverlay : UserControl
{
    private readonly Image _thumbnailImage;
    private readonly Border _viewportBorder; // 视口框
    private readonly Control _canvas;
    private double _scaleX;
    private double _scaleY;
    private readonly int _debounceDelay = 200; // 去抖延迟时间（毫秒）
    private Task? _debounceTask;
    private bool _isUpdating = false;

    /// <summary>
    /// 初始化一个新的对象。
    /// </summary>
    /// <param name="canvas">画布控件</param>
    /// <param name="width">缩略图宽度</param>
    /// <param name="height">缩略图高度</param>
    public ThumbnailOverlay(Control canvas, double width = 250, double height = 150)
    {
        _canvas = canvas;

        // 创建缩略图 Image 控件
        _thumbnailImage = new Image
        {
            Width = width, // 缩略图宽度
            Height = height, // 缩略图高度
            HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Left,
            VerticalAlignment = Avalonia.Layout.VerticalAlignment.Bottom,
            Margin = new Thickness(10),
            Stretch = Stretch.Uniform, // 确保缩略图按比例缩放
        };

        // 创建视口框
        _viewportBorder = new Border
        {
            BorderBrush = Brushes.Red,
            BorderThickness = new Thickness(2),
            HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Left,
            VerticalAlignment = Avalonia.Layout.VerticalAlignment.Top,
            IsHitTestVisible = false, // 不拦截鼠标事件
        };

        // 布局
        var overlayPanel = new Canvas
        {
            Children =
            {
                _thumbnailImage,
                _viewportBorder,
            }
        };

        Content = overlayPanel;

        // 初始化缩略图和事件绑定
        UpdateThumbnail();
        UpdateViewport();
        _canvas.PropertyChanged += (s, e) => DebounceUpdateThumbnail();

        // 处理点击和拖拽事件
        _thumbnailImage.PointerPressed += OnPointerPressed;
        _thumbnailImage.PointerMoved += OnPointerMoved;
    }

    private void DebounceUpdateThumbnail()
    {
        if (_isUpdating) return;

        // 取消现有任务并重新启动
        _debounceTask?.Dispose();
        _debounceTask = Task.Delay(_debounceDelay).ContinueWith(_ =>
        {
            Avalonia.Threading.Dispatcher.UIThread.InvokeAsync(() =>
            {
                if (_isUpdating) return;
                _isUpdating = true;

                UpdateThumbnail();
                UpdateViewport();
                _isUpdating = false;
            });
        });
    }

    private void UpdateThumbnail()
    {
        if (_canvas == null) return;

        // 渲染画布内容为 RenderTargetBitmap
        var renderBitmap = new RenderTargetBitmap(new PixelSize((int)_canvas.Bounds.Width, (int)_canvas.Bounds.Height));
        renderBitmap.Render(_canvas);

        // 设置缩略图比例
        _scaleX = _thumbnailImage.Width / _canvas.Bounds.Width;
        _scaleY = _thumbnailImage.Height / _canvas.Bounds.Height;

        // 设置到 Image
        _thumbnailImage.Source = renderBitmap;
    }

    private void UpdateViewport()
    {
        if (_canvas is ScrollViewer scrollViewer)
        {
            // 根据 ScrollViewer 的视口和内容范围计算视口框的大小和位置
            var viewportWidth = scrollViewer.Viewport.Width * _scaleX;
            var viewportHeight = scrollViewer.Viewport.Height * _scaleY;
            var viewportLeft = scrollViewer.Offset.X * _scaleX;
            var viewportTop = scrollViewer.Offset.Y * _scaleY;

            // 更新视口框的属性
            Canvas.SetLeft(_viewportBorder, viewportLeft);
            Canvas.SetTop(_viewportBorder, viewportTop);
            _viewportBorder.Width = viewportWidth;
            _viewportBorder.Height = viewportHeight;
        }
    }

    private void OnPointerPressed(object? sender, PointerPressedEventArgs e)
    {
        var pointerPoint = e.GetCurrentPoint(_thumbnailImage);
        if (pointerPoint.Properties.IsLeftButtonPressed)
        {
            AdjustCanvasViewport(pointerPoint.Position);
        }
    }

    private void OnPointerMoved(object? sender, PointerEventArgs e)
    {
        var pointerPoint = e.GetCurrentPoint(_thumbnailImage);
        if (pointerPoint.Properties.IsLeftButtonPressed)
        {
            AdjustCanvasViewport(pointerPoint.Position);
        }
    }

    private void AdjustCanvasViewport(Point thumbnailPoint)
    {
        // 主画布使用 ScrollViewer
        if (_canvas is ScrollViewer scrollViewer)
        {
            // 将缩略图位置映射到画布位置
            double targetX = thumbnailPoint.X / _scaleX;
            double targetY = thumbnailPoint.Y / _scaleY;

            // 调整滚动条位置
            scrollViewer.Offset = new Vector(targetX - scrollViewer.Viewport.Width / 2,
                                             targetY - scrollViewer.Viewport.Height / 2);

            // 更新视口框
            UpdateViewport();
        }
        else
        {
            // 如果没有 ScrollViewer，直接调整画布的 Transform
            if (_canvas.RenderTransform is TranslateTransform transform)
            {
                transform.X = -thumbnailPoint.X / _scaleX;
                transform.Y = -thumbnailPoint.Y / _scaleY;
            }
            else
            {
                _canvas.RenderTransform = new TranslateTransform
                {
                    X = -thumbnailPoint.X / _scaleX,
                    Y = -thumbnailPoint.Y / _scaleY
                };
            }
        }
    }
}
